package com.qf.weektest.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


public class MybatiesUtils {
    //单例
    private static SqlSessionFactory sqlSessionFactory;
    //线程本地缓存,
    private static ThreadLocal<SqlSession> cache = new ThreadLocal<SqlSession>();

    static {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybaties-config.xml");
            sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T getMapper(Class<T> clazz) {
        SqlSession sqlSession = getSqlSession();
        return sqlSession.getMapper(clazz);
    }
    public static SqlSession getSqlSession() {
        //需要先从缓存中查找一下是否有了sqlsession对象,如果有则直接使用
        SqlSession sqlSession = cache.get();
        if (sqlSession == null) {//线程第一次调用方法获取sqlsession
            sqlSession = sqlSessionFactory.openSession();
            cache.set(sqlSession);
            //放入线程本地缓存中
        }
        return sqlSession;
    }

    /*
提交事务
 */
    public static void commit() {
        SqlSession sqlSession = getSqlSession();
        sqlSession.commit();
        closeSqlSession();
    }

    /*
    关闭sqlSession
    注意:要把cache中的SqlSession对象清掉
     */
    public static void closeSqlSession() {
        SqlSession sqlSession = getSqlSession();
        sqlSession.close();
        cache.remove();
    }

    /**
     * 回滚事务
     */
    public static void rollback() {
        final SqlSession sqlSessoin = getSqlSession();
        sqlSessoin.rollback();
        closeSqlSession();
    }
}


